package com.kfm.web;

import com.kfm.service.FileService;
import com.kfm.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Date;

@WebServlet("/upload")
// 支持上传
@MultipartConfig(location = "E:\\temp")
public class UploadServlet extends HttpServlet {

    private FileService fileService = new FileService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 上传文件
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        Collection<Part> parts = req.getParts();
        File file = new File(Constant.UPLOAD_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        StringBuilder html = new StringBuilder("<html><body>");
        StringBuilder links = new StringBuilder();
        String ip = req.getRemoteAddr();
        ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
        for (Part part : parts) {
            // 获取上传文件的名称
            String fileName = part.getSubmittedFileName();
            try {
                part.write(Constant.UPLOAD_PATH + File.separator + fileName);
                // 构建下载链接 /download?fileName=XXX
                // http://ip:8080/download?fileName=XXX
                // 中文的时候 URL编码 URLEncoder
                String link = "/download?fileName=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8);
                int row = fileService.add(fileName.substring(0, fileName.lastIndexOf(".")), part.getSize(), new Date(), ip, link);
                if (row > 0) {
                    System.out.println("插入数据成功");
                    html.append("<h3>").append(fileName).append("上传成功</h3>");
                    links.append("<a href=").append(link).append(">下载").append(fileName).append("</a><br>");
                } else {
                    System.out.println("插入失败");
                    html.append("<h3>").append(fileName).append("上传失败失败</h3>");
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(fileName + "上传失败");
                html.append("<h3>").append(fileName).append("上传失败</h3>");
            }
            html.append("下载地址如下:<br>").append(links).append("</body></html>");
            resp.getWriter().write(html.toString());
        }
    }
}
